package tsm.network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;


public final class Message {
	private int type;
	private int commandType;
	private ByteArrayInputStream inputStream;
	private ByteArrayOutputStream outputStream;

	Message() {

	}

	public static Message createMessageToSend(int type, int commandType) {
		Message result = new Message();
		result.outputStream = new ByteArrayOutputStream();
		SerializeHelper.writeInt(type, result.outputStream);
		SerializeHelper.writeInt(commandType, result.outputStream);
		return result;
	}

	public static Message createMessageToRead(byte[] data) {
		ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
		Message result = new Message();
		result.commandType = SerializeHelper.readInt(inputStream); 
		result.type = SerializeHelper.readInt(inputStream);
		result.inputStream = inputStream;
		return result;
	}

	public int getType() {
		return type;
	}

	public int getCommandType() {
		return commandType;
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public ByteArrayOutputStream getOutputStream() {
		return outputStream;
	}

	public byte[] toByteArray() {
		return outputStream.toByteArray();
	}
	
	public void dispose() {
		try {
			if (outputStream != null) {
				outputStream.close();
				outputStream = null;
			} else if (inputStream != null) {
				inputStream.close();
				inputStream = null;
			}
		} catch (Exception e) {}
	}
}
